'use strict';

const Controller = require('egg').Controller;

class user extends Controller {
  // 登录
  async login() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      username: '',
      password: '',
    }, ctx.request.body);

    const valid = app.checkAND([
      body.username,
      body.password,
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    if (ctx.response.isLogin()) {
      ctx.body = ctx.response.successResult(2004);
      return;
    }

    const data = await service.user.login(body.username, body.password);

    if (!data) {
      ctx.body = ctx.response.errResult(4004);
      return;
    }
    if (data === 'no exists') {
      ctx.body = ctx.response.errResult(4007);
      return;
    }

    // // 保存登录状态
    ctx.response.setLogin(data);
    ctx.body = ctx.response.successResult(2002);
  }

  // 退出登录
  outlogin() {
    const { ctx } = this;
    if (ctx.response.isLogin()) {
      // 清除session cookies
      ctx.response.removeLogin();
    }
    ctx.body = ctx.response.successResult(2005);
  }

  // 注册
  async register() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      username: '',
      password: '',
      role: 2,
      nickname: '',
      phone: null,
      email: null,
    }, ctx.request.body);

    const valid = app.checkAND([
      body.username,
      body.password,
      { value: body.role, type: 'int' },
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }

    const data = await service.user.register(...Object.values(body));
    if (!data) {
      ctx.body = ctx.response.errResult(4005);
      return;
    }
    if (data === 'exists') {
      ctx.body = ctx.response.errResult(4006);
      return;
    }
    ctx.body = ctx.response.successResult(2003);
  }

  // 修改用户名、密码、权限
  async updateUserInfo() {
    const { ctx, service, app } = this;
    const body = ctx.request.merge({
      id: null,
      username: '',
      password: '',
      role: null,
    }, ctx.request.body);

    const valid = app.checkAND([
      { value: body.id, type: 'int' },
      { value: body.role, type: 'int' },
      body.username,
      body.password,
    ]);
    if (!valid) {
      ctx.body = ctx.response.errResult(4001);
      return;
    }
    const data = await service.user.update(...Object.values(body));
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001);
  }

  // 用户信息
  async userinfo() {
    const { ctx, service } = this;
    const id = ctx.response.getLogin().id;
    if (!id) {
      ctx.body = ctx.response.errResult(4002);
    }
    const data = await service.user.userinfo(id);
    if (!data) {
      ctx.body = ctx.response.errResult(4002);
      return;
    }
    ctx.body = ctx.response.successResult(2001, data);
  }
}

module.exports = user;
